from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import RetrieveModelMixin, ListModelMixin
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response
from . import models
from . import serializer
from utils.pagination import PageNumberPagination
from utils import time
from rest_framework.views import APIView


class BaseView(ListModelMixin, GenericViewSet):
    key = None

    def list(self, request, *args, **kwargs):
        response_data = cache.get(self.key)
        if not response_data:
            response = super().list(request, *args, **kwargs)
            cache.set(self.key, response.data, time())
            return response
        return Response(data=response_data)

    pass


class BookView(RetrieveModelMixin, ListModelMixin, GenericViewSet):
    queryset = models.Book.objects.filter(is_show=True, is_delete=False).order_by('total_up_num')
    serializer_class = serializer.BookModelSerializer
    pagination_class = PageNumberPagination


class BookCategoryView(RetrieveModelMixin, ListModelMixin, GenericViewSet):
    """书分类视图接口"""
    queryset = models.Category.objects.filter(is_delete=False)
    serializer_class = serializer.BookCategoryModelSerializer
    pagination_class = PageNumberPagination


class HotOrderByView(BaseView):
    """热点排序视图接口"""
    queryset = models.Book.objects.filter(is_show=True, is_delete=False).order_by('-total_up_num')[:settings.HOST_COUNT]
    serializer_class = serializer.BookModelSerializer
    # 将热点数据加入换存
    key = settings.HOST_KEY


class BookFreeView(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    """免费书接口"""
    queryset = models.Book.objects.filter(is_show=True, is_delete=False, is_free=True).order_by('total_up_num')
    serializer_class = serializer.BookModelSerializer
    pagination_class = PageNumberPagination


from rest_framework_jwt.authentication import JSONWebTokenAuthentication
import utils

class ArticleContentView(APIView):
    """获取文章内容视图接口"""
    authentication_classes = (JSONWebTokenAuthentication,)

    def get(self, request, *args, **kwargs):
        """
        1. 先判断用户登录认证是否成功, 是否是匿名用户. 匿名用户和普通登录用户只能访问免费的文章内容
        2. 再判断用户是否是vip用户
        """
        book_id = request.GET.get('book_id')
        current_section = request.GET.get('current_section')

        book = models.Book.objects.filter(pk=book_id).first()
        total_section = book.total_section

        pk = request.user.pk
        # print('request.user:', request.user)
        if pk:  # None -> 匿名
            if request.user.user_type:  # 1 -> VIP  0 -> 普通
                # VIP
                # 判断VIP用户是否到期
                is_expire = request.user.is_expire
                if is_expire:
                    return utils.APIResponse(code=0, msg='失败')

                article_instance = models.Article.objects.filter(is_show=True, is_delete=False, book=book,
                                                                 current_section=current_section).first()
                ser = serializer.ArticleModelSerializer(instance=article_instance)
                data = ser.data
                data['total_section'] = total_section
                return utils.APIResponse(data=data)
        # 匿名 和 普通
        article_instance = models.Article.objects.filter(is_show=True, is_delete=False, book=book, is_free=True,
                                                         current_section=current_section).first()
        ser = serializer.ArticleModelSerializer(instance=article_instance)
        # print('ser.data:', ser.data, type(ser.data), bool(ser.data))
        data = ser.data
        data['total_section'] = total_section
        return utils.APIResponse(data=data)
